package com.tuerks.sbahn;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.Activity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.net.Uri;
import android.os.Bundle;
import android.util.Log;

public class StationRemovalActivity extends Activity {

	// private String[][] stationList = null;
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		Log.v("s-bahn", "removal process started station");
		Uri uri = getIntent().getData();
		String station = null;
		// get ID of station to be removed and store it in station
		station = uri.getQueryParameter("station");

		Log.v("s-bahn", station);
		try {
			removeStationFromPrefs(Integer.parseInt(station));
		} catch (NumberFormatException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (JSONException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

		startActivity(new Intent(this, MainActivity.class));

	}

	public void removeStationFromPrefs(int station) throws JSONException {
		JSONObject jO = new JSONObject();
		JSONArray jA = new JSONArray();
		JSONArray jA2 = new JSONArray();

		// read prefs
		SharedPreferences myPrefs = this.getSharedPreferences("myPrefs",
				MODE_WORLD_READABLE);
		String stations = myPrefs.getString("stations", null);

		jO = new JSONObject(stations);
		jA = jO.getJSONArray("stations");
		for (int i = 0; i < jA.length(); i++) {
			if (i != station) {
				jA2.put(jA.getString(i));
			}

		}

		try {
			jO.put("stations", jA2);
		} catch (JSONException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

		SharedPreferences.Editor prefsEditor = myPrefs.edit();
		prefsEditor.putString("stations", jO.toString());
		prefsEditor.commit();

	}
}
